package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        获取当前进程ID
        log.info("当前进程ID：{}", Thread.currentThread().getId());

        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        //2、校验令牌
        try {
            log.info("开始JWT校验，进程ID：{}，token：{}", Thread.currentThread().getId(), token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);

            log.info("JWT解析成功，claims：{}", claims);
            log.info("令牌过期时间：{}", claims.getExpiration());

            Object userIdObj = claims.get(JwtClaimsConstant.USER_ID);
            log.info("原始用户ID对象：{}，类型：{}", userIdObj, userIdObj.getClass());

            Long userId = Long.valueOf(userIdObj.toString());
            log.info("转换后的用户ID：{}", userId);

            BaseContext.setCurrentId(userId);
            log.info("用户上下文设置成功，当前用户ID：{}", BaseContext.getCurrentId());

            return true;
        } catch (ExpiredJwtException ex) {
            log.error("JWT令牌已过期：{}", ex.getMessage());
            response.setStatus(401);
            return false;
        } catch (NumberFormatException ex) {
            log.error("用户ID格式转换异常：{}", ex.getMessage());
            response.setStatus(401);
            return false;
        } catch (Exception ex) {
            log.error("JWT校验未知异常：", ex);
            response.setStatus(401);
            return false;
        }
    }
}
